<template>
  <div>
    <!--    card组件-->
    <el-card id="search">
      <el-row>
        <el-col :span="20"><div class="grid-content bg-purple">
          <el-input v-model="searchModel.roleName" placeholder="角色名称" clearable></el-input>
          <el-button @click="getRoleList" type="primary" round icon="el-icon-search">搜索</el-button>
        </div></el-col>
        <!--        align是对齐属性-->
        <el-col :span="4" align="right"><div class="grid-content bg-purple-light">
          <el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>
        </div></el-col>
      </el-row>
    </el-card>
    <!--    结果列表-->
    <el-card>
      <el-table
        :data="roleList"
        stripe
        style="width: 100%"><!-- data：表格绑定数据-->
        <el-table-column label="#" width="80px" align="center">
          <!--          (pageNo - 1) * pageSize + index + 1{{scope.$index+1}},正确表示序号的表达式-->
          <template slot-scope="scope">{{(searchModel.pageNo-1) * searchModel.pageSize + scope.$index + 1}}</template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          prop="id"-->
        <!--          label="id"-->
        <!--          width="50px"-->
        <!--          align="center">-->
        <!--        </el-table-column>-->
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="200"
          align="center">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="260"
          align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button @click="openEditUI(scope.row.roleId)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
            <el-button @click="deleteRole(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--    角色信息编辑对话框-->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="roleForm" :rules="rules" ref="roleFormRef"><!--roleFormRef是角色表单引用名称，rules是校验规则-->
        <el-form-item prop="roleName" label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述" :label-width="formLabelWidth">
          <el-input v-model="roleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="menuIdList" label="权限设置" :label-width="formLabelWidth">
<!--          树形控件  :data中是菜单的一个列表-->
          <el-tree :data="menuList" :props="menuProps" show-checkbox default-expand-all node-key="menuId" ref="menuref" style="width: 60%"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入js
import roleApi from '@/api/roleManage'
import menuApi from '@/api/menuManage'
export default {
  data() {
    return {
      // 权限列表
      menuList: [],
      menuProps: {
        children: 'children',
        label: 'title'
      },
      formLabelWidth: '100px',
      // roleForm是数据对象
      roleForm: {},
      dialogFormVisible: false,
      title: '',
      // total分页
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10
      },
      roleList: [],
      // Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可
      // blur是指未输入就离开输入框
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 权限列表
    getAllMenu() {
      // 查询所有的菜单数据
      menuApi.getAllMenu().then(response => {
        this.menuList = response.data
      })
    },
    // 删除角色信息
    deleteRole(role) {
      this.$confirm(`您确认删除角色${role.roleName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleApi.deleteRoleById(role.roleId).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getRoleList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分页
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getRoleList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getRoleList()
    },
    // 获取用户列表
    getRoleList() {
      roleApi.getRoleList(this.searchModel).then(response => {
        this.roleList = response.data.rows
        this.total = response.data.total
      })
    },
    // 打开新增或者修改角色窗口，这里共用一个方法，只需要做判断即可
    openEditUI(id) {
      if (id == null) {
        this.title = '新增角色'
      } else {
        this.title = '修改角色'
        // 根据id查询角色数据
        roleApi.getRoleById(id).then(response => {
          this.roleForm = response.data
          this.$refs.menuref.setCheckedKeys(response.data.menuIdList)
        })
      }
      this.dialogFormVisible = true
    },
    // 在关闭新增页面后清除表单
    clearForm() {
      this.roleForm = {}
      this.$refs.roleFormRef.clearValidate()
      this.$refs.menuref.setCheckedKeys([])
    },
    // 新增角色保存
    saveRole() {
      // 先触发表单验证(与后端交互)
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          // 树形控件监听
          let checkedKeys = this.$refs.menuref.getCheckedKeys()
          let halfCheckedKeys = this.$refs.menuref.getHalfCheckedKeys()
          this.roleForm.menuIdList = checkedKeys.concat(halfCheckedKeys)
          // 然后提交请求给后台
          roleApi.saveRole(this.roleForm).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新表格
            this.getRoleList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },

  // 钩子函数，每次打开时调用方法
  created() {
    this.getRoleList()
    this.getAllMenu()
  }
}
</script>

<style>
#search .el-input{
  width: 150px;
  margin-right: 10px;
}
.el-dialog .el-input{
  width: 60%;
}
</style>
